const screenshot = require("screenshot-desktop")
const { WebSocketServer } = require("ws")
const http = require("http")
const getPixels = require("get-pixels")
const fs = require("fs")
const path = require("path")
const robot = require("robotjs")

const server = http.createServer()
const wss = new WebSocketServer({ server })

// 创建一个截图函数
const createScreenShot = async () => {
    const image = await screenshot({ format: "png" }); //图片的二进制流信息
    return {
        imageBuffer: image,
        base64: image.toString("base64") // 转base64给前端展示
    }
}
// 获取图片信息（宽高及路径）
const getScreenInfo = async () => {
    const { imageBuffer, base64 } = await createScreenShot()

    const filePath = path.join(__dirname, 'screenshot.png')
    fs.writeFileSync(filePath, imageBuffer)
    return new Promise((resolve,reject) => {
        getPixels(filePath, (err, pixels) => {
            if (err) reject(err)
            const shape = pixels.shape;
            resolve({
                width: shape[0],
                height: shape[1],
                base64
            })
        })
    })
}

wss.on("connection", (ws) => {
    setInterval(async () => {
        const data = await getScreenInfo()
        ws.send(JSON.stringify(data))
    }, 500)

    ws.on("message", (message) => {
        const data = JSON.parse(message)
        if (data.type == "click") {
            robot.moveMouse(data.x, data.y)
            robot.mouseClick()
        }
        console.log(data)
    })
})

server.listen(3000, () => {
    console.log("server is running")
})